/*
 * controllers_network.cpp
 *
 *  Created on: Oct 14, 2010
 *      Author: khanton
 */

#include "controllers_network.h"

void controllers_network::create_controller_connection(con_state::controller_id _id, con_connection_ptr _connection)
{
	boost::mutex::scoped_lock lck(mutex_);

	skynet_t::iterator it = skynet_.find(_id);

	if (it != skynet_.end())
	{
		throw std::logic_error("Controller with some ID allready exist in network.");
	}

	skynet_.insert(skynet_t::value_type(_id, _connection));
}

void controllers_network::remove_controller_connection(con_state::controller_id _id)
{
	boost::mutex::scoped_lock lck(mutex_);

	skynet_t::iterator it = skynet_.find(_id);

	if (it != skynet_.end())
	{
	  skynet_.erase(it);
	}
}

void controllers_network::set_connection_command_by_id(con_state::controller_id _id, con_command *_command)
{
	boost::mutex::scoped_lock lck(mutex_);

	skynet_t::iterator it = skynet_.find(_id);

	if (it == skynet_.end())
	{
		throw std::logic_error("Controller with ID not found in network.");
	}

	if(con_connection_ptr connection = it->second.lock())		// get shared ptr to session if exist
	{
	    connection->add_command_to_queue(_command); 						// start next command
	}
	else
	{
		throw std::logic_error("No control connection to controller.");
	}
}


bool controllers_network::get_controller_state_by_id(con_state::controller_id _id, con_state &_state)
{
	boost::mutex::scoped_lock lck(mutex_);

	skynet_t::iterator it = skynet_.find(_id);

	if (it == skynet_.end())
	{
		throw std::logic_error("Controller with ID not found in network.");
	}

	if(con_connection_ptr connection = it->second.lock())		// get shared ptr to session if exist
	{
		_state = connection->state_;
		return true;
	}

	return false;
}

void controllers_network::close_all_connection()
{
  while(!skynet_.empty())
  {
	skynet_t::iterator it = skynet_.begin();
	
	if(con_connection_ptr connection = it->second.lock())
	{
	  connection->close_connection();
	}
  }
}
